package com.wbt.bambootown.ui.fragment;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.gyf.barlibrary.ImmersionBar;
import com.mingle.widget.ShapeLoadingDialog;
import com.wbt.bambootown.R;
import com.wbt.bambootown.ui.activity.BaseActivity;
import com.wbt.bambootown.utils.EventCenter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;


public abstract class BaseFragment extends Fragment {
    private static final String STATE_SAVE_IS_HIDDEN = "STATE_SAVE_IS_HIDDEN";
    protected View rootView;
    private BaseActivity mActivity;
    private boolean isFirstResume = true;
    private boolean isFirstVisible = true;
    private boolean isFirstInvisible = true;
    private boolean isPrepared;
    private ImmersionBar mImmersionBar;
    private ShapeLoadingDialog mShapeLoadingDialog;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //解决内存重启add的重叠问题
        if (savedInstanceState != null) {
            boolean isSupportHidden = savedInstanceState.getBoolean(STATE_SAVE_IS_HIDDEN);
            FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
            if (isSupportHidden) {
                fragmentTransaction.hide(this);
            } else {
                fragmentTransaction.show(this);
            }
        }

        mImmersionBar = ImmersionBar.with(this);
        if (userDefaultStatus()) {
            initImmersionBar();
        } else {
            initStatusBar(mImmersionBar);
        }
    }

    /**
     * 初始化沉浸式
     */
    protected void initImmersionBar() {
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar
                .fitsSystemWindows(true)
                .statusBarColor(R.color.theme_color)
                .init();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putBoolean(STATE_SAVE_IS_HIDDEN, isHidden());
        super.onSaveInstanceState(outState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(getContentView(), container, false);
        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mActivity = (BaseActivity) getActivity();
        if (isApplyButterKnife()) ButterKnife.bind(this, view);
        if (isApplyEventBus()) EventBus.getDefault().register(this);
        initView();
        initData();

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.e("tag", "onActivityCreated");
        initPrepare();
    }

    @Override
    public void onResume() {
        super.onResume();

        if (getUserVisibleHint()) {
            onUserVisible();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (getUserVisibleHint()) {
            onUserInvisible();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            if (isFirstVisible) {
                isFirstVisible = false;
                initPrepare();
            } else {
                mImmersionBar.init();
                onUserVisible();
            }
        } else {
            onUserInvisible();
        }
    }


    private synchronized void initPrepare() {
        Log.e("tag", "basefragment initPrepare...");
        if (isPrepared) {
            Log.e("tag", "basefragment onFirstUserVisible...");
            onFirstUserVisible();
        } else {
            isPrepared = true;
        }
    }


    //是否使用默认沉浸式
    protected abstract boolean userDefaultStatus();

    protected abstract void initView();

    protected abstract void initData();

    protected abstract void onFirstUserVisible();

    /**
     * this method like the fragment's lifecycle method onResume()
     */
    protected abstract void onUserVisible();

    /**
     * when fragment is invisible for the first time
     */
    private void onFirstUserInvisible() {
        // here we do not recommend do something
    }

    /**
     * this method like the fragment's lifecycle method onPause()
     */
    protected abstract void onUserInvisible();


    @Override
    public void onDestroyView() {
        if (isApplyEventBus()) EventBus.getDefault().unregister(this);
        super.onDestroyView();

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventCenter eventCenter) {
        if (eventCenter != null) {
            onEventCome(eventCenter);
        }
    }

    public abstract void initStatusBar(ImmersionBar immersionBar);

    public abstract int getContentView();

    protected abstract boolean isApplyEventBus();

    protected abstract boolean isApplyButterKnife();

    protected abstract void onEventCome(EventCenter eventCenter);

    public void startActivity(Class cls) {
        Intent intent = new Intent(getContext(), cls);
        startActivity(intent);

    }

    /**
     * 检查是否有某项权限
     *
     * @param permission
     * @return
     */
    public boolean checkPermission(String permission) {
        if (ContextCompat.checkSelfPermission(getContext(), permission)
                != PackageManager.PERMISSION_GRANTED) {
            return false;
        }
        return true;
    }

    /**
     * 检查是否有某项权限
     *
     * @param permissions
     * @return
     */
    public boolean checkPermissions(String[] permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(getContext(), permission)
                    != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }

        return true;
    }

    /**
     * 检查是缺少的权限
     *
     * @param permissions
     * @return
     */
    public String[] checkLackPermissions(String[] permissions) {
        List<String> lackPermissions = new ArrayList<>();
        for (String permission : permissions) {
            if (!checkPermission(permission)) {
                lackPermissions.add(permission);
            }
        }
        String[] lackPermissionArray = null;
        if (lackPermissions.size() > 0) {
            lackPermissionArray = new String[lackPermissions.size()];
            lackPermissions.toArray(lackPermissionArray);
        }

        return lackPermissionArray;
    }

    public void requestSystemPermissions(String[] permissions, int requestCode) {

        requestPermissions(permissions, requestCode);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (mRequestPermission != null) {
            mRequestPermission.onRequestResult(requestCode, permissions, grantResults);
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private BaseActivity.RequestPermission mRequestPermission;

    public void setRequestPermissionListener(BaseActivity.RequestPermission requestPermission) {
        mRequestPermission = requestPermission;
    }


    public void showProgressDialog() {
        if(mShapeLoadingDialog != null && mShapeLoadingDialog.isShowing())return;
        mShapeLoadingDialog = new ShapeLoadingDialog.Builder(getContext())
                .loadText("正在加载")
                .show();
    }


    public void dismissProgressDialog() {
        if(mShapeLoadingDialog != null && mShapeLoadingDialog.isShowing()){
            mShapeLoadingDialog.dismiss();
        }
    }
}
